package com.dy.yunying.biz.service.raffle.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dy.yunying.api.entity.hongbao.HbGiftBag;
import com.dy.yunying.api.entity.raffle.GradeSortReq;
import com.dy.yunying.api.entity.raffle.RaffleActivityPrize;
import com.dy.yunying.api.enums.GiftTypeEnum;
import com.dy.yunying.api.req.raffle.RaffleActivityPrizeReq;
import com.dy.yunying.biz.dao.ads.raffle.RaffleActivityPrizeMapper;
import com.dy.yunying.biz.service.hongbao.HbGiftBagService;
import com.dy.yunying.biz.service.raffle.RaffleActivityPrizeService;
import com.dy.yunying.biz.service.sign.SignTaskConfigService;
import com.dy.yunying.biz.utils.DateUtils;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 抽奖奖品配置表服务接口实现
 *
 * @author zjz
 * @since 2022-11-07 18:36:03
 * @description 由 zjz 创建
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class RaffleActivityPrizeServiceImpl extends ServiceImpl<RaffleActivityPrizeMapper, RaffleActivityPrize> implements RaffleActivityPrizeService {

	private final HbGiftBagService hbGiftBagService;
	private final SignTaskConfigService signTaskConfigService;
	@Override
	public void saveBatchList(List<RaffleActivityPrize> list){
		this.saveBatch(list,1000);
	}

	@Override
	@Transactional(rollbackFor = Exception.class, transactionManager = "adsTransactionManager")
	public R editPrize(RaffleActivityPrizeReq req){
		RaffleActivityPrize raffleActivityPrize = new RaffleActivityPrize();
		BeanUtils.copyProperties(req, raffleActivityPrize);
		List<RaffleActivityPrize> list = baseMapper.selectList(Wrappers.<RaffleActivityPrize>lambdaQuery().eq(RaffleActivityPrize::getPrizeGrade,req.getPrizeGrade()).eq(RaffleActivityPrize::getDeleted,0));
		String info="操作成功";
		if(CollectionUtils.isNotEmpty(list)) {
			list.forEach(a -> a.setPrizeGradeSort(req.getPrizeGradeSort()));
			this.updateBatchById(list);
		}
		if(StringUtils.isNotBlank(req.getGiftStartTime())) {
			raffleActivityPrize.setGiftStartTime(DateUtils.stringToDate(req.getGiftStartTime(), DateUtils.YYYY_MM_DD_HH_MM_SS));
		}
		if(StringUtils.isNotBlank(req.getGiftEndTime())) {
			raffleActivityPrize.setGiftEndTime(DateUtils.stringToDate(req.getGiftEndTime(), DateUtils.YYYY_MM_DD_HH_MM_SS));
		}
		raffleActivityPrize.setUpdateId(Objects.requireNonNull(SecurityUtils.getUser()).getId().longValue());
		RaffleActivityPrize old = baseMapper.selectById(req.getId());
		if((old.getPrizeType()==1||req.getPrizeType()==1 ) && (!old.getPrizeType().equals(req.getPrizeType()) || !req.getGiftType().equals(old.getGiftType()))){
			hbGiftBagService.getBaseMapper().delete(Wrappers.<HbGiftBag>lambdaQuery().in(HbGiftBag::getObjectId, req.getId()).eq(HbGiftBag::getType, 5));
			old.setPrizeInventory(-1);
		}
		if(req.getPrizeType().equals(NumberUtils.INTEGER_ONE) && GiftTypeEnum.COMMON.getType().equals(req.getGiftType())){
			final HbGiftBag hbGiftBag = hbGiftBagService.getOne(Wrappers.<HbGiftBag>lambdaQuery()
					.eq(HbGiftBag::getType, 5)
					.eq(HbGiftBag::getObjectId, req.getId())
					.eq(HbGiftBag::getGiftCode, req.getGiftName())
					.last("limit 1"));
			if (Objects.isNull(hbGiftBag)) {
				HbGiftBag giftBag = new HbGiftBag();
				giftBag.setType(5);
				giftBag.setObjectId(req.getId());
				giftBag.setGiftCode(req.getGiftName());
				giftBag.setGiftAmount(req.getGiftTotalNum());
				giftBag.setUsable(2);
				giftBag.setCreateTime(new Date());
				giftBag.setUpdateTime(new Date());
				giftBag.setCreateId(Objects.requireNonNull(SecurityUtils.getUser()).getId().longValue());
				hbGiftBagService.save(giftBag);
			} else {
				HbGiftBag updateGift = new HbGiftBag();
				updateGift.setId(hbGiftBag.getId());
				updateGift.setGiftAmount(req.getGiftTotalNum());
				updateGift.setUpdateId(Objects.requireNonNull(SecurityUtils.getUser()).getId().longValue());
				updateGift.setDeleted(0);
				hbGiftBagService.updateById(updateGift);
			}
			raffleActivityPrize.setPrizeInventory(req.getGiftTotalNum());
		}
		if(req.getFile()!=null) {
			Pair<Integer, Integer> giftBag = signTaskConfigService.saveSignGiftBag(req.getFile(), 5, req.getId());
			info = "操作成功，礼包码上传成功：" + giftBag.getRight() + " 个，重复无效过滤：" + (giftBag.getLeft() - giftBag.getRight()) + " 个";
			Integer prizeInventory = old.getPrizeInventory() == -1 ? 0 : old.getPrizeInventory();
			raffleActivityPrize.setPrizeInventory(prizeInventory + giftBag.getRight());
		}
		this.baseMapper.updateById(raffleActivityPrize);
		return R.ok(null,info);
	}

	@Override
	public R editOnPrize(RaffleActivityPrizeReq req){
		if (StringUtils.isBlank(req.getPrizeGrade())) {
			return R.failed("请输入奖品品阶名称");
		}
		if (req.getPrizeGradeSort()==null) {
			return R.failed("请输入奖品品阶排序");
		}
		RaffleActivityPrize old = baseMapper.selectById(req.getId());
		String info="操作成功";
		old.setPrizeGrade(req.getPrizeGrade());
		List<RaffleActivityPrize> list = baseMapper.selectList(Wrappers.<RaffleActivityPrize>lambdaQuery().eq(RaffleActivityPrize::getPrizeGrade,req.getPrizeGrade()).eq(RaffleActivityPrize::getDeleted,0));
		if(CollectionUtils.isNotEmpty(list)) {
			list.forEach(a -> a.setPrizeGradeSort(req.getPrizeGradeSort()));
			this.updateBatchById(list);
		}
		old.setPrizeGradeSort(req.getPrizeGradeSort());

		if(old.getPrizeType()!=1){
			return R.failed("活动上线后只能追加礼包码");
		}
		if(!req.getGiftType().equals(old.getGiftType())){
			return R.failed("活动上线后礼包码类型不能修改");
		}
		if(GiftTypeEnum.COMMON.getType().equals(old.getGiftType())){
			if(req.getGiftTotalNum() < old.getPrizeCostNum()){
				return R.failed("礼包码数量不能小于已领取数量");
			}
			final HbGiftBag hbGiftBag = hbGiftBagService.getOne(Wrappers.<HbGiftBag>lambdaQuery()
					.eq(HbGiftBag::getType, 5)
					.eq(HbGiftBag::getObjectId, req.getId())
					.eq(HbGiftBag::getGiftCode, req.getGiftName())
					.last("limit 1"));
			if(Objects.isNull(hbGiftBag)) {
				HbGiftBag giftBag = new HbGiftBag();
				giftBag.setType(5);
				giftBag.setObjectId(req.getId());
				giftBag.setGiftCode(req.getGiftName());
				giftBag.setGiftAmount(req.getGiftTotalNum());
				giftBag.setUsable(2);
				giftBag.setCreateTime(new Date());
				giftBag.setUpdateTime(new Date());
				giftBag.setCreateId(Objects.requireNonNull(SecurityUtils.getUser()).getId().longValue());
				hbGiftBagService.save(giftBag);

			} else {
				HbGiftBag updateGift = new HbGiftBag();
				updateGift.setId(hbGiftBag.getId());
				updateGift.setGiftAmount(req.getGiftTotalNum());
				updateGift.setUpdateId(Objects.requireNonNull(SecurityUtils.getUser()).getId().longValue());
				updateGift.setDeleted(0);
				hbGiftBagService.updateById(updateGift);
			}

			old.setGiftTotalNum(req.getGiftTotalNum());
			old.setPrizeInventory(req.getGiftTotalNum());
		}
		if(GiftTypeEnum.UNIQUE.getType().equals(old.getGiftType()) && req.getFile()!=null){
			try {
				//校验礼包码文件并保存hb_gift_bag
				Pair<Integer, Integer> giftBag = signTaskConfigService.saveSignGiftBag(req.getFile(), 5, req.getId());
				info = "操作成功，礼包码上传成功：" + giftBag.getRight() + " 个，重复无效过滤：" + (giftBag.getLeft() - giftBag.getRight()) + " 个";
				old.setPrizeInventory(old.getPrizeInventory() + giftBag.getRight());
			} catch (IllegalArgumentException e) {
				return R.failed(e.getMessage());
			}
		}
		this.updateById(old);
		return R.ok(null,info);
	}

	@Override
	public R getGradeSort(GradeSortReq req){
		Map result =  new HashMap<>();
		List<RaffleActivityPrize> list = baseMapper.selectList(Wrappers.<RaffleActivityPrize>lambdaQuery().eq(RaffleActivityPrize::getActivityId,req.getActivityId())
				.eq(RaffleActivityPrize::getPrizeGrade,req.getPrizeGrade()).eq(RaffleActivityPrize::getDeleted,0));
		Integer prizeGradeSort = null;
		if(CollectionUtils.isNotEmpty(list)){
			prizeGradeSort = list.get(0).getPrizeGradeSort();
		}
		result.put("prizeGradeSort",prizeGradeSort);
		return R.ok(result);
	}

}